package com.jenkins.test.security;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jenkins.test.config.JwtConfig;
import com.jenkins.test.response.Result;
import com.jenkins.test.system.entity.User;
import com.jenkins.test.system.service.UserService;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.Calendar;
import java.util.UUID;

/**
 * @version V1.0.0
 * @ClassName: {@link SecurityEntryPoint}
 * @Description: SecurityEntryPoint
 * @author: Lanzhou
 * @date: 2021/6/25 14:41
 * @Copyright:2020 All rights reserved.
 */
@Slf4j
@RestController
public class SecurityEntryPoint {

    @Resource
    private LoginUserStorage loginUserStorage;

    @Resource
    private JwtConfig jwtConfig;

    @Resource
    private UserService userService;

    /**
     * 登入
     *
     * @param userVo 登入实体
     * @return 扥如
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody @Valid UserVo userVo) {
        String username = userVo.getUsername();
        String password = userVo.getPassword();
        User userByName = userService.getOne(new QueryWrapper<User>()
                .eq("username", username).last("limit 1"));
        if (null == userByName) {
            return Result.fail("用户名或者密码不正确");
        }
        byte[] encode = Base64.encodeBase64(password.getBytes());
        if (!userByName.getPassword().equals(new String(encode))) {
            return Result.fail("用户名或者密码不正确");
        }
        LoginUser loginUser = new LoginUser();
        userByName.setPassword(null);
        userByName.setAge(null);
        loginUser.setUser(userByName);

        Calendar expireTime = Calendar.getInstance();
        // 秒级别的默认是7天过期
        expireTime.add(Calendar.SECOND, jwtConfig.getExpire());
        loginUser.setExpire(expireTime.getTimeInMillis());

        // 返回给前台的JWT
        String key = UUID.randomUUID().toString().replace("-", "");
        String token = jwtConfig.createToken(SecurityConstant.TOKEN_KEY, expireTime.getTime(), key);
        loginUserStorage.cacheLoginUser(key, loginUser);
        log.info("用户: [ {} ] 已经登入系统 !", userVo.username);
        return Result.success(token);
    }


    /**
     * 登出
     *
     * @param request 请求信息
     * @return 退出系统
     */
    @GetMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        String token = request.getHeader(jwtConfig.getHeader());
        if (null == token) {
            return Result.fail("请提供有效的凭据");
        }
        DecodedJWT verify;
        try {
            verify = jwtConfig.verify(token);
        } catch (Exception e) {
            log.error("token 解析出错", e);
            return Result.fail("请提供有效的凭据");
        }

        String uuid = verify.getClaim(SecurityConstant.TOKEN_KEY).asString();
        loginUserStorage.deleteLoginUser(uuid);
        return Result.success();
    }


    @Setter
    @Getter
    static class UserVo {

        @NotBlank(message = "用户名不能为空！")
        private String username;

        @NotBlank(message = "用户密码不能为空！")
        private String password;

    }


}
